/**
 * Create specific uid (GUID, UUID, ...)
 * @param len (option, default:32) length of uid
 * @param dependStr (option) depend string, unique string create unique uid, omit to create random uid
 * @returns {string} uid string
 */
var uid = function(len, dependStr){
    len = len || 32;
    let hexs = [];
    if (typeof(dependStr) === 'string' && dependStr.length > 0){
        let hexs_tmp = [];
        for (let i = 0; i < dependStr.length; i++){
            for (let num = dependStr.charCodeAt(i);num > 0;num = Math.trunc(num / 16))
                hexs_tmp.push(num % 16);
        }
        if (hexs_tmp.length < len){
            for (let i = hexs_tmp.length; i < len; i++)
                hexs_tmp.push(0);
        }
        for (let i = 0; i < hexs_tmp.length; i++){
            hexi = i % len;
            if (hexs[hexi] === undefined)
                hexs[hexi] = 0;
            hexs[hexi] = (hexs[hexi] + hexs_tmp[i]) % 16;
        }
    } else {
        for (let i = hexs.length; i < len; i++){
            hexs[i] = Math.floor(Math.random()*16);
        }
    }
    let uidStr = '';
    for (let i = 0; i < len; i++){
        uidStr += hexs[i].toString(16);
    }
    return uidStr;
};

uid.uuid = function(dependStr){
    let uidfc = this;
    let uid = uidfc(32, dependStr);
    return uid.substr(0, 8) + '-' + uid.substr(8, 4) + '-' + uid.substr(12, 4) + '-' + uid.substr(16, 4) + '-' + uid.substr(20, 12);
};

module.exports = uid;